<template>
  <split-container class="h-full">
    <dept-tree @current-change="methods.treeNodeChange" v-model:data="tree.data" v-model:currentNode="tree.currentNode">
    </dept-tree>
    <split-container class="h-full" type="right">
      <x-card hide-search class="!border-x-0">
        <template #title>
          <el-space>
            <x-button bus-type="insert" @click="methods.add" v-auth="'sys.user.add'"></x-button>
            <x-button bus-type="update" @click="methods.update"></x-button>
            <x-button bus-type="view" @click="methods.view"></x-button>
            <x-button type="danger" bus-type="custom" :icon="ButtonIcons.del" @click="methods.disable">禁用</x-button>
            <x-button type="success" bus-type="custom" :icon="ButtonIcons.finish" @click="methods.enable">
              启用
            </x-button>
            <x-button bus-type="custom" :icon="ButtonIcons.export" @click="methods.export">导出</x-button>
          </el-space>
          <el-space>
            <el-input v-model="condition.name" placeholder="名称"></el-input>
            <el-checkbox label="查询已禁用" :true-label="-1" :false-label="0" v-model="condition.status" border>
            </el-checkbox>
            <x-button bus-type="query" @click="methods.query"></x-button>
          </el-space>
        </template>
        <template #main>
          <x-table v-bind="table" v-model:selection="table.selection" @page-change="methods.tablePageChange"
            @row-click="methods.tableRowClick">
            <template #status="{ row }">
              <el-tag :type="row.status === 0 ? 'success' : 'warning'">{{ row.status === 0 ? '正常' : '禁用' }}</el-tag>
            </template>
          </x-table>
        </template>
      </x-card>
      <x-card hide-search class="w-250px">
        <template #title>
          <el-space>
            <x-button :icon="ButtonIcons.finish" type="primary" @click="methods.saveRoles">保存角色</x-button>
          </el-space>
        </template>
        <template #main>
          <x-table v-model:selection="roleTable.selection" v-bind="roleTable" ref="roleTableRef" row-key="id"></x-table>
        </template>
      </x-card>
    </split-container>
    <editor v-model:visable="editor.visable" v-bind="editor" :tree-data="tree.data" @saved="methods.query"></editor>
  </split-container>
</template>
<script lang="ts" setup>
import { IDeptTreeNodeItem } from '~/types/sys/IDeptTreeNode'
import DeptTree from '../dept/DeptTree.vue'
import DeptTreeHook from '../dept/DeptTreeHook'
import { UserQueryCondition } from '~/types/sys/UserQueryCondition'
import { SysUser } from '~/types/sys/SysUser'
import UserService from '~/service/sys/UserService'
import { ButtonIcons } from '~/components/xview/button'
import { reactive, ref } from 'vue'
import { initTable } from '~/hooks/TableHooks'
import { ITableColumn } from '~/components/xview/table/ITableColumn'
import Editor from './editor.vue'
import elpUtil from '~/utils/elp'
import { EditorHooks } from '~/hooks'
import { SysRole } from '~/types/sys/SysRole'
import { RoleService } from '~/service/sys'
import XTable from '~/components/xview/table/XTable.vue'

const condition = reactive<UserQueryCondition>(new UserQueryCondition())
let currentUser: SysUser = null
const roleTableRef = ref<InstanceType<typeof XTable>>(null)
const editor = EditorHooks.init<SysUser>()

const { tree } = DeptTreeHook()

const table = initTable<SysUser>([
  {
    label: '状态',
    prop: 'status',
    slot: true,
    width: 70
  },
  {
    label: '登录名',
    prop: 'userName',
    width: 150
  },
  {
    label: '姓名',
    prop: 'realName',
    width: 150
  },
  {
    label: '所属单位',
    prop: 'deptName'
  },
  {
    label: '有效期',
    prop: 'expDate',
    width: 150,
    formatter: (row: SysUser): string => {
      return row.expDate === null ? '' : row.expDate.substring(0, 10)
    }
  }
] as ITableColumn[])

const roleTable = initTable<SysRole>([
  {
    label: '拥有角色',
    prop: 'roleName'
  }
] as ITableColumn[])
roleTable.showPagination = false

let tempRoles: SysRole[] = []

RoleService.list().then((rows: SysRole[]) => {
  roleTable.tableData = rows
  tempRoles = rows
})

const methods = {
  async query() {
    const data = await UserService.query(condition)
    table.fillPagedData(data)
  },
  export() {
    const statusListSource = {
      "0": "正常",
      "-1": "禁用"
    }
    UserService.export(condition, table.tableColumns, (column) => {
      //在列配置回调中，可以指定对应column的序列化格式或者是需要进行字典项替换的值
      switch (column.prop) {
        case 'expDate':
          column.format = "yyyy/MM/dd"
          break
        case 'status':
          column.listSource = statusListSource
          break
      }

    })
  },
  add() {
    editor.insert({
      deptId: tree.currentNode.id,
      sort: 0,
      expDate: '2099-01-01 00:00:00'
    } as SysUser)
  },
  update() {
    if (table.selection.length == 0) {
      elpUtil.msg.warning('请先选择需要编辑的数据行')
      return
    }
    editor.update(table.selection[0])
  },
  view() {
    if (table.selection.length == 0) {
      elpUtil.msg.warning('请先选择需要编辑的数据行')
      return
    }
    editor.view(table.selection[0])
  },
  async disable() {
    if (table.selection.length == 0) return
    if (await elpUtil.msg.confirm('是否禁用所选用户')) {
      const ids = table.selection.map((t) => t.id)
      await UserService.disable(ids)
      elpUtil.msg.success('用户禁用成功')
      methods.query()
    }
  },
  async enable() {
    if (table.selection.length == 0) return
    const ids = table.selection.map((t) => t.id)
    await UserService.enable(ids)
    elpUtil.msg.success('用户启用成功')
    methods.query()
  },
  tablePageChange(page: number) {
    condition.paging.current = page
    methods.query()
  },
  async tableRowClick(row: SysUser) {
    currentUser = row
    const roles = await UserService.userRoles(currentUser.id)
    if (roles.length > 0) {
      const selectedRoles = tempRoles.filter((t) => roles.indexOf(t.id) >= 0)
      console.log('roles', selectedRoles)
      roleTableRef.value!.setSelections(selectedRoles)
    } else {
      roleTableRef.value!.clearSelection()
    }
  },
  treeNodeChange(node: IDeptTreeNodeItem) {
    condition.levelCode = node.levelCode
    methods.query()
  },
  async saveRoles() {
    if (currentUser === null) return
    const selectedRoles = roleTable.selection
    const roleIds = selectedRoles.length === 0 ? [] : selectedRoles.map((t) => t.id)
    await UserService.saveRoles(currentUser.id, roleIds)
    elpUtil.msg.success('授权角色已成功保存')
  }
}
</script>
